export function httpRequest(url, data, headers) {
  return new Promise((resolve, reject) => {
    dd.httpRequest({
      url: url,
      method: 'POST',
      data: data,
      headers: headers,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

export function judge(res,fun) {
	if(res?.status==500||res?.status==502){
		dd.showToast({
		  content: '状态码500/502,服务端报错',
		  type: 'fail',
		  duration: 5000,
		})
	}
	else if(res?.status==200){
		if(res?.data?.success){
			if(res?.data?.status_code==0){
				// temp=true;
				// console.log("temp "+temp);
				fun();
			}
			else if(res?.data?.status_code==1){
				dd.showToast({
				  content: '登陆过期，请重新登录',
				  type: 'fail',
				  duration: 5000,
				})
			
			}
			else if(res?.data?.status_code==4||res?.data?.status_code==14){
				dd.showToast({
				  content: '服务器端错误',
				  type: 'fail',
				  duration: 5000,
				})
			}
		}
		else{
			// dd.showToast({
			//   content: '返回的success为false',
			//   type: 'fail',
			// })
			const appKey = 'ding4xyxwffxxjgnhdr2';
			
			// 获取code
			dd.getAuthCode({
			    success:function(res){
					console.log('authCode'+res.authCode);
					// 获取
					dd.httpRequest({
						url: 'http://113.15.231.21:180/dd/ding_oauth',
						method: 'POST',
						data: {
							app_key:appKey,
							code:res.authCode
						},
						dataType: 'json',
						success: function(res1) {
							dd.setStorageSync({
							  key: 'storageData',
							  data: {
							   ding_userid: res1.data.result.ding_userid,
							   sessionid: res1.data.result.sessionid,
							   user_id: res1.data.result.user_id
							  }
							});
							
						},
						fail: function(res1) {
							dd.showToast({
								content: "请求ding_oauth接口失败 "+res1,
								type: 'fail',
							})
						}
					});
					
			    },
				fail:function(err){
					dd.showToast({
						content: "获取authCode失败 "+err,
						type: 'fail',
					})
				}

			});
		}
		if(res?.data?.message!='查询成功'){
			dd.showToast({
			  content: res?.data?.message,
			  type: res?.data?.status_code==0?'success':'fail',
			  duration: res?.data?.status_code == 0 ? 3000 : 5000,
			})
		}

	}
	else{
		dd.showToast({
		  content: '出现除500、502、200以外的状态码',
		  type: 'fail',
		  duration: 5000,
		})
	}
	
}

export function message(isSuccess,text) {
	dd.showToast({
		content: text,
		type: isSuccess,
		duration: isSuccess=='fail' ? 5000 : 3000,
	})
}
